package com.ktwlsoft.archivemanage.domain.business.businessService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.*;
import com.ktwlsoft.archivemanage.domain.dao.entity.*;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.account.AccountManageModifyRequest;
import com.ktwlsoft.archivemanage.payload.account.AccountManageSaveRequest;
import com.ktwlsoft.archivemanage.payload.account.ResetUnitPasswordRequest;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveLogRequest;
import com.ktwlsoft.archivemanage.service.utils.PassWordUtils;
import com.ktwlsoft.archivemanage.service.utils.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 账号管理
 *
 * @author zhuhe on 2019/10/28 10:18
 * @version 1.0
 */
@Component
public class AccountManageService {

    /**
     * 账号
     */
    private final AccountRepositoryService accountRepositoryService;

    private final PasswordEncoder passwordEncoder;

    /**
     * 用户角色关系
     */
    private final UserRolesRepositoryService userRolesRepositoryService;
    private final ArchiveUnitRepositoryService archiveUnitService;

    /**
     * 图片
     */
    private final ImgsService imgsService;

    public AccountManageService(AccountRepositoryService accountRepositoryService, PasswordEncoder passwordEncoder, UserRolesRepositoryService userRolesRepositoryService, ImgsService imgsService, ArchiveUnitRepositoryService archiveUnitService) {
        this.accountRepositoryService = accountRepositoryService;
        this.passwordEncoder = passwordEncoder;
        this.userRolesRepositoryService = userRolesRepositoryService;
        this.imgsService = imgsService;
        this.archiveUnitService=archiveUnitService;
    }

    /**
     * 账号管理列表 on 2019/10/28 10:21
     *
     * @param keyWords keyWords
     * @return Result<?>
     */
    public Result<?> findPage(int pn, int pageSize, String keyWords) {

       
        Account account = new Account();
        account.setId(null);
        account.setCreatedAt(null);
        account.setCreator(null);
        account.setCreatorId(null);
        account.setUpdateAt(null);
        if (keyWords != null && !"".equals(keyWords.trim())) {
            account.setKeyWords(keyWords);
        }
        PageInfo<Account> pageInfo = accountRepositoryService.findPageNotUnit(pn, pageSize, account);
        if (pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            for (Account account1 : pageInfo.getList()) {
                //account1.setSex(null);
                account1.setEmail(null);
                account1.setIdentityType(null);
                account1.setIdentityNum(null);
                account1.setPassword(null);
                //account1.setProfile(null);
                account1.setPasswordStrength(null);
            }
        }
        return Result.ok(pageInfo);
    }

    /**
     * 账号管理详情 on 2019/10/28 11:00
     *
     * @param id id
     * @return Result<?>
     */
    public Result<?> getById(Long id) {
        if (id == null || id <= 0) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        Account account = accountRepositoryService.getById(id);
        if (account == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        //保留为null的字段
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(account, SerializerFeature.WriteMapNullValue));
        if (account.getIdentityType() != null && !"".equals(account.getIdentityType())) {
            Imgs imgs = new Imgs();
            imgs.setId(null);
            imgs.setCreatedAt(null);
            imgs.setCreator(null);
            imgs.setCreatorId(null);
            imgs.setUpdateAt(null);
            imgs.setBusinessId(account.getId());
            imgs.setBusinessType(account.getIdentityType());
            jsonObject.put("identityFile", imgsService.findList(imgs));
        }
        return Result.ok(jsonObject);
    }

    /**
     * 账号管理新增 on 2019/10/28 11:07
     *
     * @param request request
     * @return Result<?>
     */
    public Result<?> save(AccountManageSaveRequest request) {
        if(!PassWordUtils.checkPasswordIsStrong(request.getPassword())){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("密码不能为空并且密码长度不小于8位数,包含小写字母,大写字母,数字和特殊字符");
        }
        Account checkUnique = new Account();
        checkUnique.setTeleNum(request.getTeleNum());
        checkUnique.setRoleName("管理");
        List<Account> accounts = accountRepositoryService.checkUnique(checkUnique);
        if (accounts != null && accounts.size() > 0) {
            for (Account account : accounts) {
                if (account.getUserName().equalsIgnoreCase(request.getUserName())) {
                    return Result.body(null, ResultType.CHECK_ERROR).withMessage("用户名重复");
                }
                if (account.getTeleNum().equals(request.getTeleNum())) {
                    return Result.body(null, ResultType.CHECK_ERROR).withMessage("手机号重复");
                }
            }
        }
        Account account = new Account();
        BeanUtils.copyProperties(request, account);
        if (account.getEnable() == null) {
            account.setEnable(true);
        }
        //证件上传
        if (request.getIdentityFile() != null && request.getIdentityFile().size() > 0) {
            if (request.getIdentityType() == null) {
                return Result.body(null, ResultType.CHECK_ERROR).withMessage("证件类型不能为空");
            }
            ImgUploadService.imgUploads(request.getIdentityFile(), String.valueOf(account.getId()), request.getIdentityType());
        }
        //图片上传
        if (request.getProfileFile() != null) {
            List<MultipartFile> multipartFiles = Lists.newArrayList();
            multipartFiles.add(request.getProfileFile());
            List<Imgs> imgss = ImgUploadService.imgUploads(multipartFiles, String.valueOf(account.getId()), "PROFILE");
            if (imgss != null && imgss.size() > 0) {
                account.setProfile(String.valueOf(imgss.get(0).getId()));
            }
        }
        account.setPasswordStrength(UserUtils.testingPasswordStrength(account.getPassword()));
        //加密
        account.setPassword(passwordEncoder.encode(account.getPassword()));
        try {
            accountRepositoryService.insert(account);
            //新增用户角色关系
            if (account.getRoleId() != null && account.getRoleName() != null) {
                UserRoleRelation userRoleRelation = new UserRoleRelation();
                userRoleRelation.setRoleId(account.getRoleId());
                userRoleRelation.setRoleName(account.getRoleName());
                userRoleRelation.setAccountId(account.getId());
                userRoleRelation.setUserName(account.getUserName());
                userRolesRepositoryService.insert(userRoleRelation);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(null, ResultType.SAVING_ERROR);
        }
        return Result.ok(account.getId());
    }

    /**
     * 账号管理修改 on 2019/10/28 11:13
     *
     * @param request request
     * @return Result<?>
     */
    public Result<?> modify(AccountManageModifyRequest request) {
        if (request.getId() == null || request.getId() <= 0) {
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        boolean b = false;
        Account checkUnique = new Account();
        checkUnique.setTeleNum(request.getTeleNum());
        checkUnique.setRoleName("管理");
        List<Account> accounts = accountRepositoryService.checkUnique(checkUnique);
        if (accounts != null && accounts.size() > 0) {
            for (Account account : accounts) {
                if (!account.getId().equals(request.getId())) {
                    if (account.getUserName().equalsIgnoreCase(request.getUserName())) {
                        return Result.body(request, ResultType.CHECK_ERROR).withMessage("用户名重复");
                    }
                    if (account.getTeleNum().equals(request.getTeleNum())) {
                        return Result.body(request, ResultType.CHECK_ERROR).withMessage("手机号重复");
                    }
                }
            }
        }
        Account account = new Account();
        BeanUtils.copyProperties(request, account);
        if (account.getPassword() != null) {
            if(!PassWordUtils.checkPasswordIsStrong(request.getPassword())){
                return Result.body(null, ResultType.CHECK_ERROR).withMessage("密码不能为空并且密码长度不小于8位数,包含小写字母,大写字母,数字和特殊字符");
            }
            account.setPasswordStrength(UserUtils.testingPasswordStrength(account.getPassword()));
            if (account.getPassword() != null && !"".equals(account.getPassword())) {
                account.setPassword(passwordEncoder.encode(account.getPassword()));
                b = true;
            }
        }
        //证件上传
        if (request.getIdentityFile() != null && request.getIdentityFile().size() > 0) {
            //删除
            ImgUploadService.deleteByBIdAndBType(account.getId(), account.getIdentityType());
            if (request.getIdentityType() == null) {
                return Result.body(null, ResultType.CHECK_ERROR).withMessage("证件类型不能为空");
            }
            ImgUploadService.imgUploads(request.getIdentityFile(), String.valueOf(account.getId()), request.getIdentityType());
        }
        //图片上传
        if (request.getProfileFile() != null) {
            //删除
            ImgUploadService.deleteByBIdAndBType(request.getId(), "PROFILE");
            //上传
            List<MultipartFile> multipartFiles = Lists.newArrayList();
            multipartFiles.add(request.getProfileFile());
            List<Imgs> imgss = ImgUploadService.imgUploads(multipartFiles, String.valueOf(account.getId()), "PROFILE");
            if (imgss != null && imgss.size() > 0) {
                account.setProfile(String.valueOf(imgss.get(0).getId()));
            }
        }
        try {
            accountRepositoryService.update(account);
            //新增用户角色关系
            if (account.getRoleId() != null && account.getRoleName() != null) {
                List<UserRoleRelation> userRoleRelations = userRolesRepositoryService.getByAccountId(account.getId());
                if (userRoleRelations != null && userRoleRelations.size() > 0) {
                    List<Long> ids = Lists.newArrayList();
                    for (UserRoleRelation userRoleRelation : userRoleRelations) {
                        ids.add(userRoleRelation.getId());
                    }
                    userRolesRepositoryService.deleteByIds(ids);
                }
                UserRoleRelation userRoleRelation = new UserRoleRelation();
                userRoleRelation.setRoleId(account.getRoleId());
                userRoleRelation.setRoleName(account.getRoleName());
                userRoleRelation.setAccountId(account.getId());
                userRoleRelation.setUserName(account.getUserName());
                userRolesRepositoryService.insert(userRoleRelation);
            }
            if (b) {
                OperationRepositoryService.saveLog(new SaveLogRequest(
                        OperationLog.OperationType.PASSWORD,
                        "重置密码",
                        "账号管理",
                        OperationLog.BusinessType.SYSTEM
                ));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(null, ResultType.UPDATE_ERROR);
        }
        return Result.ok(account.getId());
    }

    /**
     * 账号管理删除 on 2019/10/28 11:19
     *
     * @param id id
     * @return Result<?>
     */
    public Result<?> deleteById(Long id) {
        if (id == null || id <= 0) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        Account account = accountRepositoryService.getById(id);
        if (account == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        try {
            accountRepositoryService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(id, ResultType.DELETE_ERROR);
        }
        return Result.ok(account.getRealName());
    }

    public Result<?> getTeacherInfo(Long id) {
        if (id == null || id <= 0) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        Account account = accountRepositoryService.getById(id);
        if (account == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        Account resAccount = new Account();
        resAccount.setId(account.getId());
        resAccount.setRoleName(account.getRoleName());
        resAccount.setDepartmentName(account.getDepartmentName());
        resAccount.setRealName(account.getRealName());
        resAccount.setSex(account.getSex());
        resAccount.setTeleNum(account.getTeleNum());
        resAccount.setIdentityType(account.getIdentityType());
        resAccount.setIdentityNum(account.getIdentityNum());
        resAccount.setProfile(account.getProfile());
        resAccount.setIntroduce(account.getIntroduce());
        resAccount.setUserName(account.getUserName());
        //保留为null的字段
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(resAccount, SerializerFeature.WriteMapNullValue));
        if (resAccount.getIdentityType() != null && !"".equals(resAccount.getIdentityType())) {
            Imgs imgs = new Imgs();
            imgs.setId(null);
            imgs.setCreatedAt(null);
            imgs.setCreator(null);
            imgs.setCreatorId(null);
            imgs.setUpdateAt(null);
            imgs.setBusinessId(resAccount.getId());
            imgs.setBusinessType("IDCARD");
            jsonObject.put("identifyUrl", imgsService.findList(imgs));
        }
        return Result.ok(jsonObject);
    }


    /**
     * 更新老师介绍
     *
     * @param id
     * @param introduce
     * @return
     */
    public Result<?> updateIntroduce(Long id, String introduce) {
        if (id == null || id <= 0) {
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        Account account = accountRepositoryService.getById(id);
        if (account != null) {
            account.setIntroduce(introduce);
        }
        try {
            accountRepositoryService.getAccountMapper().updateIntroduce(account);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(null, ResultType.UPDATE_ERROR);
        }
        return Result.ok(account.getId());
    }

    /**
     * 更新老师介绍
     *
     * @return
     */
    public Result<?> getInstructors() {
        Account account = new Account();
        account.setRoleName("业务指导员");
        account.setId(null);
        account.setCreatedAt(null);
        account.setUpdateAt(null);
        List<Account> accountList = accountRepositoryService.findList(account);
        return Result.ok(accountList);
    }

    /**
     * 更新老师介绍
     *
     * @return
     */
    public Result<?> getAllInstructors() {
        Account account = new Account();
        account.setRoleName("业务指导员");
        account.setId(null);
        account.setCreatedAt(null);
        account.setUpdateAt(null);
        List<Account> accountList = accountRepositoryService.findList(account);
        return Result.ok(accountList.stream().map(value ->{
            JSONObject object = new JSONObject();
            object.put("id",value.getId());
            object.put("realName",value.getRealName());
            object.put("teleNum",value.getTeleNum());
            return object;
        }).collect(Collectors.toList()));
    }

    /**
     * 重置密码
     * @param request
     * @return
     */
    public Object resetPassword(ResetUnitPasswordRequest request) {
        ArchiveUnit archiveUnit = archiveUnitService.getByAccount(request.getAccount());
        if(archiveUnit == null){
            return Result.body(request, ResultType.CHECK_ERROR).withMessage("该用户不存在");
        }
        if(!PassWordUtils.checkPasswordIsStrong(request.getNewPassword())){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("密码不能为空并且密码长度不小于8位数,包含小写字母,大写字母,数字和特殊字符");
        }
        archiveUnit.setPassword(passwordEncoder.encode(request.getNewPassword()));
        Account account = accountRepositoryService.getById(archiveUnit.getAccountId());
        try {
            archiveUnitService.update(archiveUnit);
            if(account != null){
                account.setPassword(passwordEncoder.encode(request.getNewPassword()));
                account.setPasswordStrength(UserUtils.testingPasswordStrength(request.getNewPassword()));
                accountRepositoryService.update(account);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(request, ResultType.UPDATE_ERROR);
        }
        return Result.body(null,ResultType.BUSINESS_SUCCESS);
    }
}